package com.xgry.bpm.api.base.login;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xgry.bpm.api.base.userInfo.entity.UserInfo;
import com.xgry.bpm.api.base.userInfo.service.UserInfoService;
import com.xgry.bpm.api.base.userinforole.entity.UserInfoRole;
import com.xgry.bpm.api.base.userinforole.service.UserInfoRoleService;
import com.xgry.bpm.common.enums.Const;
import com.xgry.bpm.common.enums.LoginTypeEnum;
import com.xgry.bpm.common.enums.Tools;
import com.xgry.bpm.common.enums.UserState;
import com.xgry.bpm.common.utils.MD5Util;
import com.xgry.bpm.common.utils.Result;
import com.xgry.bpm.config.shiro.UserToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Controller
@RequestMapping()
public class LoginController {
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserInfoRoleService userInfoRoleService;



    @RequestMapping(value="/login.do",method= RequestMethod.POST)
    @ResponseBody
    public Result loginByUserNamePassword(@RequestParam("userName") String userName,
                                          @RequestParam("password") String password,
                                          @RequestParam("code") String code,HttpSession session){

        String sessionCode = (String)session.getAttribute(Const.SESSION_SECURITY_CODE);
        if (!sessionCode.equalsIgnoreCase(code)) {
            return Result.fail("验证码错误！",code);
        }

        UserInfo queryUser = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("userName", userName));
        if (null == queryUser) {
            return Result.fail("未查询到用户！");
        }

        if (!Objects.equals(MD5Util.MD5(password), queryUser.getPassword())){
            return Result.fail("账号密码不正确！");
        }

        if (queryUser.getUserState().equals(UserState.LOCK.getCode())) {
            return Result.fail("对不起，您的账号已被锁定！暂时无法登录！");
        }

        List<Integer> roleIds = userInfoRoleService.list(new QueryWrapper<UserInfoRole>() {{
            this.eq("userInfoId", queryUser.getUserId());
        }}).stream().map(UserInfoRole::getRoleId).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(roleIds)) {
            return Result.fail("对不起，您账号未绑定角色！");
        }

        session.setMaxInactiveInterval(36000);
        queryUser.setLoginDate(new Date());
        queryUser.setLoginCount(null == queryUser.getLoginCount()?1:queryUser.getLoginCount()+1);
        userInfoService.updateById(queryUser);

        /*roleIds.toArray(new String[]);
        roleIds.stream().map(String::).collect(Collectors.joining(","));
        queryUser.setRoleIdList();*/
        Subject subject = SecurityUtils.getSubject();
        subject.login(new UserToken(userName, MD5Util.MD5(password), LoginTypeEnum.NORMAL.getValue()));

        return Result.success("登录成功!",queryUser);
    }

    /**
     * 用户登录
     * @param request
     * @param session
     * @param userName
     * @return
     * @throws ServletException
     * @throws IOException*/
    @RequestMapping(value="/login1.do",method= RequestMethod.POST,produces = "application/json; charset=utf-8")
    @ResponseBody
    public String loginPost(HttpServletResponse response, HttpServletRequest request, HttpSession session, @RequestParam String userName, @RequestParam String password, @RequestParam String code) throws Exception {
        String sessionCode = (String)session.getAttribute(Const.SESSION_SECURITY_CODE);
        ModelAndView mv = new ModelAndView();
        JSONObject json1 = new JSONObject();
        String errInfo = "";
        if(Tools.notEmpty(sessionCode) && sessionCode.equalsIgnoreCase(code)){
            QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
            userInfoQueryWrapper.eq("userName",userName);
            UserInfo userInfo = userInfoService.getOne(userInfoQueryWrapper);
            if (userInfo == null) {
                mv.addObject("status", "error");
                mv.addObject("message", "该用户名未注册，请先注册后使用！！");
                json1.put("msg", "该用户名未注册，请先注册后使用！！");
                errInfo = "该用户名未注册，请先注册后使用！！";
                //mv.setViewName("/pages/login");
            }else if (!MD5Util.MD5(password).equals(userInfo.getPassword())) {
                mv.addObject("status", "error");
                mv.addObject("message", "用户名或密码错误，请重新输入！！");
                json1.put("msg", "用户名或密码错误，请重新输入！！");
                errInfo = "用户名或密码错误，请重新输入！！";
                //mv.setViewName("/pages/login");
            }else if (userInfo.getUserState() == UserState.LOCK.getCode()) {
                mv.addObject("status", "error");
                mv.addObject("message", "对不起，您的账号已被锁定！！");
                json1.put("msg", "对不起，您的账号已被锁定！！");
                errInfo = "对不起，您的账号已被锁定！！";
                //mv.setViewName("/pages/login");
            }else {
                session.setMaxInactiveInterval(36000);
                userInfo.setLoginDate(new Date());
                if(userInfo.getLoginCount()==null || userInfo.getLoginCount().equals("")) {
                    userInfo.setLoginCount(1);
                }else {
                    userInfo.setLoginCount(userInfo.getLoginCount()+1);
                }
//				webSocketSession = session
//				MyWebSocket.addWebSocketSet(userInfo, session);
                UserToken token = new UserToken(userName, MD5Util.MD5(password), LoginTypeEnum.NORMAL.getValue());
                Subject subject = SecurityUtils.getSubject();
                subject.login(token);
                userInfoService.updateById(userInfo);
                QueryWrapper<UserInfoRole> UserInfoRoleQueryWrapper = new QueryWrapper<>();
                UserInfoRoleQueryWrapper.eq("userInfoId",userInfo.getUserId());
                List<UserInfoRole> list = userInfoRoleService.list(UserInfoRoleQueryWrapper);
                session.setAttribute(Const.SESSION_ROLE_RIGHTS, list);
                session.setAttribute(Const.SESSION_USER, userInfo);
                session.removeAttribute(Const.SESSION_SECURITY_CODE);
            }
        }else{
            errInfo = "验证码输入有误！";
            json1.put("msg", "验证码输入有误！");
            //mv.setViewName("/pages/login");
        }
        if(Tools.isEmpty(errInfo)){
            System.out.println(session.getAttribute(Const.SESSION_USER));
            //request.getRequestDispatcher("/miniUI/frame/frame1/pages/index.html").forward(request,response);
            //mv.setViewName("redirect:ToIndex.do");
            QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
            userInfoQueryWrapper.eq("userName",userName);
            UserInfo userInfo = userInfoService.getOne(userInfoQueryWrapper);            json1.put("user", userInfo);
            json1.put("msg", "登录成功");
        }else{
            mv.addObject("errInfo", errInfo);
            mv.addObject("userName",userName);
            mv.addObject("password",password);
            json1.put("msg", errInfo);
            json1.put("userName", userName);
            //mv.setViewName("/pages/login");
            //request.getRequestDispatcher("/pages/login.html").forward(request,response);
        }
        return json1.toString();
    }

    /**
     * 跳转Login页面
     */
    @RequestMapping("/ToLogin.do")
    @ResponseBody
    public ModelAndView ToLogin() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/pages/login.html");
        return mv;
    }

    @RequestMapping("/")
    public String index(Model model, HttpServletResponse response) {
        model.addAttribute("name", "simonsfan");
        return "/index";
    }


    /**
     * 跳转index页面
     */
    @RequestMapping("/ToIndex.do")
    @ResponseBody
    public ModelAndView ToIndex() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/miniUI/frame/frame1/pages/index");
        return mv;
    }

}
